package com.hanhai.zrb.backend.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.hanhai.common.web.controller.BaseController;
import com.hanhai.zrb.api.biz.service.FeedbackService;
import com.hanhai.zrb.api.biz.util.XlsUtils;
import com.hanhai.zrb.backend.admin.model.BackendUser;
import com.hanhai.zrb.backend.util.BackendLoginUtil;
import com.hanhai.zrb.model.user.Feedback;
import com.hanhai.zrb.model.user.dto.FeedbackDto;
@Controller
@RequestMapping("feedbackExcle")
public class FeedbackExcleController extends BaseController{
		@Resource
		private FeedbackService feedbackService;
	
	    @RequestMapping("exportExcel") 
	    public void exportExcel(FeedbackDto feedbackDto,HttpServletRequest request, HttpServletResponse response)     
	    throws Exception {   


	    	
            List<Feedback> list =feedbackService.searchFeedbackList(feedbackDto);
	        HSSFWorkbook wb = feedbackService.export(list);    
	        response.setContentType("application/vnd.ms-excel");  
	        String fileName ="意见反馈";
			response.setHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("gbk"),"iso-8859-1")+".xls");  //转码之后下载的文件不会出现中文乱码
	        OutputStream ouputStream = response.getOutputStream();    
	        wb.write(ouputStream);    
	        ouputStream.flush();    
	        ouputStream.close();    
	   }  
	    
	    
		@RequestMapping(value = "/uploadExcel")
		public void uploadFile(HttpServletRequest request,HttpServletResponse response) throws IOException{
			
			
			BackendUser user = BackendLoginUtil.getCurrentUser();
			if(null!=user && !"".equals(user)){
				
			}
			Map<String, Object> map = new HashMap<String, Object>();
			String status = "";
			String info = "";
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	        MultipartFile file = multipartRequest.getFile("uploadExcel");  
	        if (file != null && file.getSize() > 0) {
	            String fileName = file.getOriginalFilename();
	            long fileSize = file.getSize();
	            String extend = fileName.substring(fileName.lastIndexOf(".") + 1);
	    		if (!"xls".equalsIgnoreCase(extend) && !"xlsx".equalsIgnoreCase(extend)) {//文件格式
	    			status = "n";
	    			info = "|请选择excel格式文件上传！|";
	    		} else if (fileSize > 1024 * 1024 * 2) {//文件大小(2Mb)
	    			status = "n";
	    			info = "|导入文件大小不得大于2Mb！|";
	    		} else if(null!=user && !"".equals(user)){
	    			InputStream inputStream = null;
	    			try {
						inputStream = file.getInputStream();
						//解析xls
						InputStream is = file.getInputStream();
						List<List<Object>> list = XlsUtils.readExcel(is, extend, 1, 17);
						if (list != null && !list.isEmpty()) {
							List data = new ArrayList();
							// 效验数据...
							StringBuilder infos = new StringBuilder();
							int sucNum = 0;
							try {
								if (list != null && !list.isEmpty()) {
									for (int i = 0; i < list.size(); i++) {
										List<Object> obj = list.get(i);
										if (obj.size() >= 8) {
											String id = (String) obj.get(0);
											String statusStr = (String) obj.get(6);
											String description = (String) obj.get(7);
											try {
												if(id.indexOf(".")>0){
													id = id.substring(0, id.indexOf("."));
												}
													Feedback feedback = feedbackService.selectByPrimaryKey(Long.valueOf(id));
		                                            if(null!=feedback && !"".equals(feedback)){
		                                            	Integer statusInt= "已受理".equals(statusStr)?1:0;
		                                            	feedback.setStatus(statusInt);
		                                            	feedback.setAccpUname(user.getLoginName());
		                                            	feedback.setDescription(description);
		                                            	feedback.setAccpTime(new Date());
		                                            	feedbackService.updateByPrimaryKey(feedback);
		                                            	sucNum++;
		                                            }
												} catch (Exception e) {
													// TODO: handle exception
													e.printStackTrace();
												}
										}
									}
									infos.append("|导入成功|");
								}
							} catch (Exception e) {
								infos.append("|导入失败，系统出现异常|");
							}
							status = "y";
			    			info = infos.toString();
						}else{
							status = "n";
							info = "|文件数据错误！|";
						}
					} catch (Exception e) {
						status = "n";
						info = "|文件数据错误！|";
					} finally{
						if (inputStream != null) {
							try {
								inputStream.close();
							} catch (IOException e) {
								logger.error("IO异常", e);
							}
						}
					}
	    		}else{
	    			status = "n";
	    			info = "|请先登录后台|";
	    		}
			}else{
				status = "n";
				info = "|请选择上传文件！|";
			}
	        map.put("status", status);
	        map.put("info", info);
			String str=JSONObject.toJSONString(map);
			response.getWriter().write(str);

		}


}
